<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { getUserInfo } from '@/api/auth'
import { LOGIN_PAGE } from '@/router/config'
import { useUserStore } from '@/store'
import { useTokenStore } from '@/store/token'

definePage({
  style: {
    // 隐藏头部导航栏
    navigationStyle: 'custom',
    backgroundColor: '#FFFFFF',
    // 启用安全区域适配
    safeAreaInsetTop: true,
    safeAreaInsetBottom: true,
  },
})

const userStore = useUserStore()
const tokenStore = useTokenStore()
const { userInfo } = storeToRefs(userStore)

// 实际获取用户信息的函数
async function fetchRealUserInfo() {
  try {
    // 直接调用auth.ts中的getUserInfo接口
    const res = await getUserInfo()
    console.log('获取到的用户信息:', res)
    return res.data
  }
  catch (error) {
    console.error('获取用户信息失败:', error)
    throw error
  }
}

// 页面加载时获取用户信息
onLoad(() => {
  // 如果用户已登录，则获取用户信息
  if (tokenStore.hasLogin) {
    fetchRealUserInfo()
      .then((res) => {
        console.log('设置用户信息:', res)
        // 将获取到的完整用户信息响应设置到store中
        // 现在store的setUserInfo方法可以直接处理完整的response
        userStore.setUserInfo(res.userInfo)
      })
      .catch((error) => {
        console.error('设置用户信息失败:', error)
      })
  }
})

// 菜单项配置
const menuItems = [
  {
    id: 'profile',
    icon: 'i-carbon-user-profile',
    title: '我的资料',
    subtitle: '查看和编辑个人信息',
    route: '/pages-sub/settings/user-profile',
  },
  { id: 'notification', icon: 'i-solar:bell-bing-broken', title: '通知设置', subtitle: '管理通知方式和偏好', route: '/pages-sub/settings/notification' },
  {
    id: 'security',
    icon: 'i-solar:lock-keyhole-minimalistic-broken',
    title: '账户安全',
    subtitle: '密码和安全设置',
    route: '/pages-sub/settings/security',
  },
  {
    id: 'about',
    icon: 'i-solar:info-circle-broken',
    title: '关于我们',
    subtitle: '应用版本和版权信息',
    route: '/pages-sub/settings/about',
  },
]

// 处理菜单项点击
function handleMenuClick(item: typeof menuItems[0]) {
  // 这里可以添加权限检查或其他逻辑
  uni.navigateTo({
    url: item.route,
  })
}

// 去登录
function handleLogin() {
  uni.redirectTo({
    url: LOGIN_PAGE,
  })
}

// 退出登录
function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清空用户信息
        tokenStore.logout()
        // 执行退出登录逻辑
        uni.showToast({
          title: '退出登录成功',
          icon: 'success',
        })
        // 跳转到登录页
        uni.reLaunch({
          url: LOGIN_PAGE,
        })
      }
    },
  })
}
</script>

<template>
  <view class="profile-container bg-white pt-12 text-slate-900 pb-safe">
    <!-- 用户信息区域 -->
    <view class="user-info-section p-6">
      <view class="flex items-center">
        <view class="relative">
          <image
            :src="userInfo?.userInfo?.avatar || '/static/images/default-avatar.png'"
            mode="aspectFill"
            class="h-18 w-18 border-3 border-yellow-200 rounded-full border-solid"
            lazy-load
          />
          <view v-if="tokenStore.hasLogin" class="absolute bottom-0 right-0 h-6 w-6 flex items-center justify-center border-2 border-white rounded-full bg-green-500">
            <i class="i-carbon:thumbs-up-double-filled text-xs text-white" />
          </view>
        </view>
        <view class="ml-4">
          <view class="flex items-center">
            <text class="text-xl font-bold">{{ userInfo?.userInfo?.realname || userInfo?.userInfo?.username || '未登录' }}</text>
          </view>
          <text class="mt-1 block text-sm text-slate-500">部门：{{ userInfo?.userInfo?.sysDepart?.departName || '-' }}</text>
          <text class="mt-1 block text-sm text-slate-500">手机：{{ userInfo?.userInfo?.phone || userInfo?.userInfo?.phone || '-' }}</text>
        </view>
      </view>
    </view>

    <!-- 菜单列表 -->
    <view class="menu-section mt-2 px-4">
      <view
        v-for="item in menuItems"
        :key="item.id"
        class="menu-item mb-3 flex items-center justify-between border border-slate-100 rounded-lg bg-slate-50 p-3"
        @click="handleMenuClick(item)"
      >
        <view class="flex items-center">
          <view class="mr-3 h-10 w-10 flex items-center justify-center rounded-lg bg-slate-100">
            <i class="text-slate-700" :class="item.icon" />
          </view>
          <view>
            <text class="text-slate-900 font-medium">{{ item.title }}</text>
            <text class="mt-1 block text-xs text-slate-500">{{ item.subtitle }}</text>
          </view>
        </view>
        <i class="i-carbon-chevron-right text-slate-300" />
      </view>
    </view>

    <!-- 根据登录状态显示不同按钮 -->
    <view class="logout-section mt-8 px-4">
      <!-- 未登录状态 - 显示去登录按钮 -->
      <button
        v-if="!tokenStore.hasLogin"
        class="w-full flex items-center justify-center rounded-lg bg-green-500 py-3 text-white font-medium"
        @click="handleLogin"
      >
        <i class="i-solar:login-3-broken bold mr-2 text-xl" />
        去登录
      </button>
      <!-- 已登录状态 - 显示退出登录按钮 -->
      <button
        v-else
        class="w-full flex items-center justify-center border border-slate-100 rounded-lg bg-slate-50 py-3 text-red-500 font-medium"
        @click="handleLogout"
      >
        <i class="i-carbon-logout mr-2" />
        退出登录
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.profile-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;
  /* 确保容器占满整个视口高度 */
  box-sizing: border-box;
}

/* 为用户信息区域添加额外的顶部内边距，避免内容太靠近顶部 */
.user-info-section {
  padding-top: 24px;
}

.menu-item {
  transition: all 0.2s ease;
}

.menu-item:active {
  background-color: #f1f5f9;
}

button {
  line-height: normal;
}

button::after {
  border: none;
}

/* 底部按钮区域添加底部内边距 */
.logout-section {
  padding-bottom: 24px;
}
</style>
